/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import tools.StringTools;
import database.DBConnectionFactory;

/**
 * This class represents a non agression pact (NAP)
 * 
 * 
 */
public class Nap implements BotObject {
   /**
    * Removes the specified NAP
    * 
    * @param args
    *           specifies the KD with which to remove the NAP
    * @return true if the NAP is successfully deleted
    */
   public static boolean deleteFromDB(final String... args) {
	  boolean out = false;
	  if (args.length < 1)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("DELETE FROM nap WHERE location = ?");
		 ps.setString(1, args[0]);
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns a list of all NAPs
    * 
    * @return a List of Nap objects
    */
   public static List<Nap> getNaps() {
	  List<Nap> out = new LinkedList<Nap>();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM nap");
		 rs = ps.executeQuery();
		 while (rs.next()) {
			out.add(new Nap(rs.getString("location"), rs.getTimestamp("enddate").getTime(), rs.getTimestamp("settime").getTime()));
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   private String kd = "";

   private Long endDate = 0L;

   private Long settime = 0L;

   public Nap(final String kd, final Long endDate, final Long settime) {
	  this.kd = kd;
	  this.settime = settime;
	  if (endDate.equals(0L)) { // if no end date is set, set it to 2 years into the future
		 Calendar cal = Calendar.getInstance();
		 cal.add(Calendar.YEAR, 2);
		 this.endDate = cal.getTimeInMillis();
	  } else {
		 this.endDate = endDate;
	  }
   }

   public Long getEndDate() {
	  return endDate;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  // not used
	  return new LinkedList<String>();
   }

   public String getKd() {
	  return kd;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (StringTools.isNullOrEmpty(getKd()) || getEndDate() == null || getSettime() == null)
		 return out;
	  out.put("End Date", new Date(getEndDate()));
	  out.put("KD", getKd());
	  out.put("Set Time", new Date(getSettime()));
	  return out;
   }

   public Long getSettime() {
	  return settime;
   }

   @Override
   public boolean saveToDB() {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(getKd()) || getEndDate() == null || getSettime() == null
			|| getEndDate() < Calendar.getInstance().getTimeInMillis())
		 return out;
	  PreparedStatement ps = null;
	  try {
		 deleteFromDB(getKd());

		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("INSERT INTO nap VALUES(?,?,?)");
		 ps.setString(1, getKd());
		 ps.setTimestamp(2, new Timestamp(getEndDate()));
		 ps.setTimestamp(3, new Timestamp(getSettime()));
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }
}
